import { useEffect, useRef, useState } from 'react'
import {
  NavBar,
  Tabs,
  Card,
  Button,
  SearchBar,
  PullToRefresh,
  InfiniteScroll,
  Toast,
} from 'antd-mobile'
// import { LeftOutline } from 'antd-mobile-icons'
import { useNavigate } from 'react-router-dom'
import styles from './index.module.css'
import placeholder from '../../assets/placeholder.png'
import { fetchLeasedOutList, fetchPendingLeaseList } from '../../services/api'

type LeaseItem = {
  id: string | number
  contractNo: string
  title: string
  buildingInfo?: string
  floor: string
  roomNo: string
  area: string
  tenant: string
  idNo: string
  phone: string
  rentPerMonth: string
  deposit: string
  // 已退租列表费用字段
  complianceMoney?: string
  outstandingAmount?: string
  refundAmount?: string
}

export default function LeaseTerminationManage() {
  const navigate = useNavigate()
  const [tabKey, setTabKey] = useState<'pending' | 'finished'>('pending')
  const [keyword, setKeyword] = useState('')
  const [items, setItems] = useState<LeaseItem[]>([])
  const [hasMore, setHasMore] = useState(true)
  const [loaded, setLoaded] = useState(false)
  const pageRef = useRef(1)
  const sizeRef = useRef(10)
  const loadingRef = useRef(false)

  function toItem(it: any): LeaseItem {
    return {
      id: it.id,
      contractNo: it.agreementNum || it.contractNo || '—', // 已退租列表使用 agreementNum
      title: it.buildingEstateName || it.projectName || '—',
      buildingInfo: it.houseNo ? `-${it.houseNo}` : '',
      floor: it.buildingUnitName || '—',
      roomNo: it.houseNo || '—',
      area: it.houseTypeName || '—',
      tenant: it.name || it.applicationName || '—', // 已退租列表使用 name
      idNo: it.identityNum || '—', // 已退租列表可能没有此字段
      phone: it.phone || '—',
      rentPerMonth: `${it.monthlyRent}元`,
      deposit: typeof it.bankDeposit === 'number' ? `${it.bankDeposit}元` : '—', // 已退租列表可能没有此字段
    }
  }

  async function queryPage(reset = false) {
    if (loadingRef.current) return
    loadingRef.current = true
    const params: any = { current: pageRef.current, size: sizeRef.current }
    if (tabKey === 'finished' && keyword.trim()) params.keyword = keyword.trim()
    const api = tabKey === 'pending' ? fetchPendingLeaseList : fetchLeasedOutList
    const res = await api(params).catch(() => null)
    if (res) {
      const list = (res.records || []).map((it: any) => toItem(it))
      setItems(prev => (reset ? list : [...prev, ...list]))
      const noMore = (res.current || 1) >= (res.pages || 1)
      setHasMore(!noMore)
      if (!noMore) pageRef.current += 1
    }
    loadingRef.current = false
    setLoaded(true)
  }

  useEffect(() => {
    pageRef.current = 1
    setItems([])
    setHasMore(true)
    queryPage(true)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [tabKey])

  useEffect(() => {
    if (tabKey === 'finished') {
      pageRef.current = 1
      setItems([])
      setHasMore(true)
      queryPage(true)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [keyword])

  async function loadMore() {
    await queryPage(false)
  }

  async function onRefresh() {
    pageRef.current = 1
    setItems([])
    setHasMore(true)
    setLoaded(false)
    await queryPage(true)
    Toast.show('已刷新')
  }

  return (
    <div className={styles['lease-page']}>
      <NavBar className={styles['nav-title']} back={null}>
        退租列表
      </NavBar>

      <div className={styles['lease-header']}>
        <div className={styles['lease-tabs']}>
          <Tabs activeKey={tabKey} onChange={key => setTabKey(key as any)}>
            <Tabs.Tab title={<span className={styles['tab-title']}>待退租</span>} key="pending" />
            <Tabs.Tab title={<span className={styles['tab-title']}>已退租</span>} key="finished" />
          </Tabs>
        </div>
      </div>

      {tabKey === 'finished' && (
        <div className={styles['lease-search']}>
          <SearchBar value={keyword} onChange={setKeyword} placeholder="搜索合同号/小区/租户" />
        </div>
      )}

      <div className={styles['lease-list-scroll']}>
        <PullToRefresh onRefresh={onRefresh}>
          <div className={styles['lease-list']}>
            {loaded && items.length === 0 ? (
              <div className={styles['empty-wrap']}>
                <img src={placeholder} alt="empty" className={styles['empty-image']} />
                <div className={styles['empty-text']}>暂无数据</div>
              </div>
            ) : (
              <>
                {items.map(item => (
                  <Card
                    key={item.id}
                    style={{ borderRadius: 8, marginBottom: 12 }}
                    onClick={() => navigate(`/lease-audit/${item.id}`)}
                  >
                    <div className={styles['lease-contract']}>合同号：{item.contractNo}</div>

                    <div
                      className={styles['lease-row']}
                      onClick={e => {
                        if (tabKey === 'finished') {
                          e.stopPropagation()
                          return
                        }
                      }}
                    >
                      <div className={styles['lease-info']}>
                        <div className={styles['lease-title']}>
                          {item.title}
                          <span className={styles['lease-sub']}>{item.buildingInfo}</span>
                        </div>

                        <div className={styles['lease-tags']}>
                          <span className={styles['lease-chip']}>{item.floor}</span>
                          <span className={styles['lease-chip']}>{item.roomNo}</span>
                        </div>

                        <div className={styles['lease-text']}>租期：2025年6月1日—2025年12月1日</div>
                        <div className={styles['lease-text']}>租户：{item.tenant}</div>
                        <div className={styles['lease-text']}>身份证号：{item.idNo}</div>
                        <div className={styles['lease-text']}>电话：{item.phone}</div>

                        {/* 待退租列表显示月租金和保证金 */}
                        {tabKey === 'pending' && (
                          <>
                            <div className={styles['lease-text']}>月租金：{item.rentPerMonth}</div>
                            <div className={styles['lease-text']}>保证金：{item.deposit}</div>
                          </>
                        )}

                        {/* 已退租列表显示费用信息 */}
                        {tabKey === 'finished' && (
                          <>
                            <div className={styles['lease-text']}>费用：{item.rentPerMonth}</div>
                          </>
                        )}
                      </div>

                      <div
                        className={styles['lease-action']}
                        onClick={e => {
                          if (tabKey === 'finished') {
                            return
                          } else {
                            e.stopPropagation()
                            navigate(`/lease-audit/${item.id}`)
                          }
                        }}
                      />
                    </div>
                    <div className={styles['lease-card-btn-wrap']}>
                      <Button
                        size="mini"
                        className={`${styles['lease-card-btn']} ${
                          tabKey === 'finished' ? styles['lease-card-btn-wait'] : ''
                        }`}
                        style={{ fontSize: 10, height: 26, padding: '0 10px', lineHeight: '26px' }}
                        onClick={e => {
                          e.stopPropagation()
                          if (tabKey === 'finished') {
                            return
                          } else {
                            navigate(`/lease-audit/${item.id}`)
                          }
                        }}
                      >
                        {tabKey === 'finished' ? '待财务确认' : '立即审核'}
                      </Button>
                    </div>
                  </Card>
                ))}
              </>
            )}
            <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
          </div>
        </PullToRefresh>
      </div>
    </div>
  )
}
